package org.jeecg.module.flow.meter.tcpserver.tcpServer.handler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.module.flow.meter.tcpserver.dto.Cat1MessageDto;
import org.jeecg.module.flow.meter.tcpserver.factory.FlowMeterMessageFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @Author: 86176
 * @Date: 2024-05-21 8:28
 * @Version: 1.0
 */
@Slf4j
@Service
public class TcpConnectionHandler extends SimpleChannelInboundHandler<Cat1MessageDto> {

    private final static Map<String, ChannelHandlerContext> map = new ConcurrentHashMap<>();

    private static TcpConnectionHandler tcpConnectionHandler;
    @Resource
    private FlowMeterMessageFactory meterMessageFactory;

    @PostConstruct
    public void init() {
        tcpConnectionHandler = this;
        tcpConnectionHandler.meterMessageFactory = this.meterMessageFactory;
    }


    /**消息处理*/
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Cat1MessageDto msg) throws Exception {
        tcpConnectionHandler.meterMessageFactory.parseMessage(msg,ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("Channel {} 已激活", ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("Channel {} 已处于不活动状态", ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("Channel {} 发生异常:", ctx.channel(), cause);
        ctx.close();
    }
}
